<template>
  <ContainerGroup>
    <Container style="margin-bottom:10px;">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="handleSearch"
        @reset="handlerReset"
      />
    </Container>
    <Container height="fill" display="flexY">
      <OperationContainer class="operation-box">
        <Button icon="reset" :loading="cjLoading" @click="handleCollection">采集财务信息</Button>
        <span>最近采集时间：{{ cjTime }}</span>
        <div class="opt-right">
          <Button type="info" icon="cloudy" :loading="xzmbLoading" @click="handleExport(0)">下载模板</Button>
          <el-upload
            ref="upload"
            style="display:inline-block;"
            :show-file-list="false"
            :on-change="handlechange"
            class="upload-demo"
            action
            :auto-upload="false"
          >
            <el-button :loading="drLoading" class="btn-import el-icon-upload2">导入</el-button>
          </el-upload>
          <Button type="info" :loading="dcLoading" icon="export" @click="handleExport(1)">导出</Button>
          <el-upload
            ref="upload"
            style="display:inline-block;"
            :show-file-list="false"
            :on-change="handleFpjfChange"
            class="upload-demo"
            action
            :auto-upload="false"
          >
            <el-button :loading="dfpjfrLoading" class="btn-import el-icon-upload2">导入分批经费</el-button>
          </el-upload>
        </div>
      </OperationContainer>
      <Table
        :columns="tableColumns"
        :loading="tableLoading"
        :index="true"
        :data="tableData"
        :pagination="{
          total: total,
          current: currentPage,
          pageSize: pageSize,
        }"
        :row-class-name="tabelRowClassName"
        @paginationChange="pageChange"
      >
        <template #caozuo="{row}">
          <Tooltip v-if="row.status!==0" content="编辑" icon="edit" @click="handleEidt(row)" />
          <Tooltip v-if="row.status!==0" content="删除" icon="delete" @click="handleDelete(row)" />
        </template>
      </Table>
      <!-- 新增、编辑 -->
      <Drawer
        :title="title"
        :visible="isShow"
        :header-color="'#e7ecf8'"
        :loading="confirmLoading"
        width="560px"
        :footer-btns="[
          {
            text: '确定',
            type: 'primary',
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @cancel="isShow = false"
        @submit="handleSubmit"
      >
        <div class="form-box">
          <el-form
            v-if="isShow"
            ref="ruleForm"
            size="mini"
            :model="ruleForm"
            :rules="rules"
            label-width="125px"
            class="demo-ruleForm"
          >
            <el-form-item label="财务编码：">
              <el-input v-model.trim="ruleForm.financialCode" placeholder="请输入财务编码" disabled />
            </el-form-item>
            <el-form-item label="项目编号：" prop="projectCode">
              <el-input v-model.trim="ruleForm.projectCode" placeholder="请输入项目编号" />
            </el-form-item>
            <el-form-item label="项目类别：" prop="entryId">
              <el-select
                v-model="ruleForm.entryId"
                style="width:100%;"
                placeholder="请选择项目类别"
                filterable
                clear
              >
                <el-option
                  v-for="item in optionList2"
                  :key="item.entryCode"
                  :label="item.entryName"
                  :value="item.entryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="项目简称：" prop="financialName">
              <el-input v-model.trim="ruleForm.financialName" placeholder="请输入项目简称" />
            </el-form-item>
            <el-form-item label="项目全称：" prop="projectInfo">
              <el-input v-model.trim="ruleForm.projectInfo" placeholder="请输入项目全称" />
            </el-form-item>
            <el-form-item label="总金额：">
              <el-input v-model.trim="ruleForm.total" disabled />
            </el-form-item>
            <el-form-item label="项目经费：">
              <!-- <el-button-group>
                <el-button
                  v-for="(item,index) in buttonList"
                  :key="index"
                  :type="btnIndex===index?'primary':'info'"
                  @click="handleToggle(index)"
                >{{ item.label }}</el-button>
              </el-button-group>-->
              <div class="btn-xx">
                <!-- 分批配置经费 -->
                <div style="margin-bottom:-8px;position:relative;">
                  <div
                    v-for="(jfItem,jfIndex) in ruleForm.allocations"
                    :key="jfIndex"
                    class="label-fpjf"
                  >
                    <el-date-picker
                      v-model="jfItem.createTime"
                      type="month"
                      placeholder="选择日期时间"
                      value-format="yyyy-MM"
                      style="width:420px;margin-right:10px;"
                    />
                    <el-input v-model.trim="jfItem.appropriationBalance" placeholder="请输入此次分批经费金额" />
                    <span style="margin-left:5px;margin-right:50px;">元</span>
                    <div class="z-j-box">
                      <span class="el-icon-circle-plus-outline" @click="handlePlusBtn" />
                      <span
                        v-if="jfIndex>0"
                        class="el-icon-circle-close"
                        @click="handleCloseBtn(jfItem, jfIndex)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="项目负责人：" prop="userId">
              <el-select
                v-model="ruleForm.userId"
                placeholder="请输入关键词"
                filterable
                clear
                style="width:100%;"
                remote
                reserve-keyword
                :remote-method="remoteMethod"
                :loading="scLoading"
                @change="handleUserBlur"
              >
                <el-option
                  v-for="item in leaderList"
                  :key="item.userName"
                  :label="item.realName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="可查看人：" prop="viewPerson">
              <el-select
               ref="viewSelect"
                v-model="ruleForm.viewPerson"
                placeholder="请输入"
                filterable
                style="width:100%;"
                remote
                multiple
                reserve-keyword
                :remote-method="remoteMethodSearch"
                @change="handleViewChange"
              >
                <el-option
                  v-for="item in viewList"
                  :key="item.userName"
                  :label="item.realName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属科室：">
              <el-select
                v-model="ruleForm.deptCode"
                placeholder="请选择所属科室"
                filterable
                clear
                style="width:100%;"
                disabled
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.deptCode"
                  :label="item.deptName"
                  :value="item.deptCode"
                />
              </el-select>
              <!-- <el-cascader
                v-model="ruleForm.deptCode"
                style="width:100%;"
                :options="deptList"
                :props="casprops"
                :show-all-levels="false"
              />-->
            </el-form-item>
            <el-form-item label="往期收入总金额：">
              <div class="label-text">
                <el-input v-model.trim="ruleForm.income" placeholder="请输入往期收入总金额" disabled />
                <span>元</span>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </Drawer>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  projectInfoPage,
  projectInfoDelete,
  projectInfoUpdate,
  projectInfoType,
  projectInfoLeader,
  projectInfoDept,
  projectInfoDownloadex,
  projectInfoDownload,
  projectInfoImport,
  getProjectDetail,
  collectFinancialData,
  importAllocation
} from '@/apis/specialFunds/systermSetting'
export default {
  name: 'ProjectInfoManagement', // 项目信息管理
  data() {
    return {
      cjTime: '',
      casprops: {
        label: 'deptName',
        value: 'deptCode',
        children: 'childrens',
        // checkStrictly: true,
        emitPath: true
      },
      deptList: [],
      leaderList: [],
      viewList: [],
      value1: '',
      btnIndex: 0,
      buttonList: [
        {
          label: '总金额',
          value: 1
        },
        {
          label: '分批配置经费',
          value: 2
        }
      ],
      confirmLoading: false,
      title: '编辑项目信息',
      isShow: false,
      optionList2: [],
      fyList: [],
      szlxList: [],
      ruleForm: {
        financialCode: '',
        projectCode: '',
        financialName: '',
        projectInfo: '',
        entryId: '',
        total: '',
        userId: '',
        deptCode: '',
        income: '',
        allocations: [
          {
            createTime: '',
            appropriationBalance: ''
          }
        ],
        viewPerson:[]
      },
      rules: {
        projectCode: [
          { required: true, message: '请输入项目编号', trigger: 'blur' }
        ],
        entryId: [
          { required: true, message: '请选择项目类别', trigger: 'change' }
        ],
        financialName: [
          { required: true, message: '请输入项目简称', trigger: 'blur' }
        ],
        projectInfo: [
          { required: true, message: '请输入项目全称', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请选择项目负责人', trigger: 'change' }
        ]
      },
      xzmbLoading: false,
      dcLoading: false,
      drLoading: false,
      cjLoading: false,
      filterElements: [
        {
          key: 'financialCode',
          type: 'input',
          label: '财务编码',
          value: ''
        },
        {
          key: 'projectCode',
          type: 'input',
          label: '项目编号',
          value: ''
        },

        {
          key: 'leaderName',
          type: 'input',
          label: '项目负责人',
          value: ''
        },
        {
          key: 'projectName',
          type: 'input',
          label: '项目全称/简称',
          value: '',
          width: 150
        },
        {
          key: 'entryId',
          type: 'Select',
          label: '项目类别',
          value: '',
          itemLabel: 'entryName',
          itemValue: 'entryCode',
          options: [],
          filterable: true,
          clearable: true
        }
      ],
      tableColumns: [
        {
          title: '财务编码',
          dataIndex: 'financialCode'
        },
        {
          title: '项目编号',
          dataIndex: 'projectCode'
        },
        {
          title: '项目类别',
          dataIndex: 'entryName'
        },
        {
          title: '项目简称',
          dataIndex: 'financialName'
        },
        {
          title: '项目全称',
          dataIndex: 'projectInfo'
        },
        {
          title: '项目负责人',
          dataIndex: 'userName'
        },
        // {
        //   title: '所属科室',
        //   dataIndex: 'deptName'
        // },

        // {
        //   title: '创建时间',
        //   dataIndex: 'etlTime'
        // },
        {
          title: '操作',
          width: 160,
          type: 'otherTag',
          dataIndex: 'caozuo'
        }
      ],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      currentRow: null,
      dfpjfrLoading: false,
      scLoading: false,
      seeList: []
    }
  },
  watch: {
    'ruleForm.allocations': {
      handler(value) {
        this.ruleForm.total = value.reduce((prev, cur) => {
          return (
            Number(prev.appropriationBalance) ||
            0 + Number(cur.appropriationBalance) ||
            0
          )
        }, 0)
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getSelect(2, '项目类别') // 项目类别
    this.getDeptList()
  },
  methods: {
    remoteMethod(query) {
      this.leaderList = []
      this.getLeaderName(query)
    },
    remoteMethodSearch(query) {
      this.viewList = []
      this.getLeaderNameSearch(query)
    },
    handleViewChange(val) {
      console.log(val);
      this.seeList = []
      val.forEach(it => {
        const obj = {
          userName: it,
          
        }
        this.seeList.push(obj)
        
      })
     
      
      
    },
    tabelRowClassName({ row, rowIndex }) {
      if (row.status === 0) {
        return 'warning-row'
      }
      return ''
    },
    getDeptList() {
      // 科室列表
      projectInfoDept().then(res => {
        if (res.data.code === 200) {
          this.deptList = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleUserBlur(id) {
      this.leaderList.forEach(item => {
        if (item.userName === id) {
          this.ruleForm.deptCode = item.deptCode
        }
      })
    },
    getLeaderName(name) {
      this.scLoading = true
      projectInfoLeader({
        userName: name
      }).then(res => {
        this.scLoading = false
        if (res.data.code === 200) {
          this.leaderList = res.data.data
          // this.viewList = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    getLeaderNameSearch(name) {
      this.scLoading = true
      projectInfoLeader({
        userName: name
      }).then(res => {
        this.scLoading = false
        if (res.data.code === 200) {
          // this.leaderList = res.data.data
          
          this.viewList = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    getSelect(type, code) {
      projectInfoType({
        type: code
      }).then(res => {
        if (res.data.code === 200) {
          this[`optionList${type}`] = res.data.data
          this.filterElements[4].options = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleSetFormValue(row) {
      getProjectDetail({
        financialCode: row.financialCode
      }).then(res => {
        if (res.data.code === 200) {
          const result = res.data.data
          this.btnIndex = result.allocations.length > 0 ? 1 : 0
          this.viewList = result.viewPersonsSource
          // this.otherViewList=res.data.data.viewPersons||[]
          
          this.seeList = result.viewPersons
          for (const key in this.ruleForm) {
            if (key === 'allocations') {
              this.ruleForm['allocations'] =
                result['allocations'].length === 0
                  ? [
                    {
                      createTime: '',
                      appropriationBalance: '',
                      financialCode: this.currentRow?.financialCode,
                      financialName: this.currentRow?.financialName
                    }
                  ]
                  : result['allocations']
            } else if (key === 'userId') {
              if (result['userId']) {
                this.ruleForm['userId'] = result['userId']
              }
              this.getLeaderName(result['userName'] ?? '')
            } else if(key === 'viewPerson') {
              this.ruleForm['viewPerson'] = result.viewPersons?.map(item => item.userName)
            } else {
              if (result[key]) {
                this.ruleForm[key] = result[key]
              }
            }
          }
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handlePlusBtn(item) {
      this.ruleForm.allocations.push({
        createTime: '',
        appropriationBalance: '',
        financialCode: this.currentRow?.financialCode,
        financialName: this.currentRow?.financialName
      })
    },
    handleCloseBtn(item, index) {
      this.ruleForm.allocations.splice(index, 1)
    },
    handleToggle(index) {
      this.btnIndex = index
    },
    handleSubmit() {
      const param = this.ruleForm
      let allocationArr = []
      try {
        allocationArr = this.ruleForm.allocations.filter(item => {
          if (
            item.appropriationBalance !== '' &&
            item.appropriationBalance !== undefined &&
            item.appropriationBalance !== null
          ) {
            if (!item.createTime) {
              throw new Error('请选择日期')
            }
            item.createTime = item.createTime + '-01'
            item.financialCode = this.currentRow?.financialCode
            item.financialName = this.currentRow?.financialName
            return item
          }
        })
      } catch (error) {
        this.$message.warning(error)
        return
      }

      // console.log('allocationArr', allocationArr)
      param.allocations = allocationArr
      if (this.ruleForm.income) {
        if (isNaN(this.ruleForm.income)) {
          this.$message.warning('往期收入总金额需要数字格式')
          return
        }
      }
      param.entryName = this.optionList2.find(
        item => item.entryCode === this.ruleForm.entryId
      )?.entryName
      
      param.userName = this.leaderList.find(
        item => item.userName === this.ruleForm.userId
      )?.realName
      param.isClose = this.currentRow?.isClose
      param.deptName = this.deptList.find(
        item => item.deptCode === this.ruleForm.deptCode
      )?.deptName
      
      const uniqueData = []
      const seenUserNames = new Map()
      this.seeList?.forEach(item => {
        if (!seenUserNames.has(item.userName)) {
          seenUserNames.set(item.userName, true);
          uniqueData.push(item)
        }
      })
     
      // this.viewList=[...this.viewList,...this.otherViewList]
      param.viewPersons = uniqueData?.map(item => {
        return {
          userName: item.userName,
          // realName: this.viewList.find(it => item.userName === it.userName)?.realName,
          financialCode: this.ruleForm.financialCode
        }
      })

      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.confirmLoading = true
          projectInfoUpdate(param).then(res => {
            this.confirmLoading = false
            this.isShow = false
            if (res.data.code === 200) {
              this.getData()
              // this.otherViewList = []
              this.$message.success(res.data.message)
            } else {
              this.$message.error(res.data.message)
            }
          })
        } else {
        //   console.log('error submit!!')
          return false
        }
      })
    },
    handlechange(file, fileList) {
      // 导入
      const fileType = file.name.substr(file.name.lastIndexOf('.')).trim()
      if (fileType !== '.xlsx' && fileType !== '.xls') {
        this.$message.warning('请选择Excel格式的文件导入！')
        return
      }
      const files = file.raw
      const formData = new FormData()
      formData.append('file', files)
      this.drLoading = true
      projectInfoImport(formData).then(res => {
        this.drLoading = false
        if (res.data.code === 200) {
          this.$message.success('上传成功')
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleFpjfChange(file, fileList) {
      // 导入分配经费
      const fileType = file.name.substr(file.name.lastIndexOf('.')).trim()
      if (fileType !== '.xlsx' && fileType !== '.xls') {
        this.$message.warning('请选择Excel格式的文件导入！')
        return
      }
      const files = file.raw
      const formData = new FormData()
      formData.append('file', files)
      this.dfpjfrLoading = true
      importAllocation(formData).then(res => {
        this.dfpjfrLoading = false
        if (res.data.code === 200) {
          this.$message.success('上传成功')
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleExport(type) {
      // 导出
      let api = projectInfoDownload
      const param = {
        financialCode: this.$refs.filterForm.getParms()?.financialCode || '',
        leaderName: this.$refs.filterForm.getParms()?.leaderName || '',
        projectName: this.$refs.filterForm.getParms()?.projectName || '',
        projectCode: this.$refs.filterForm.getParms()?.projectCode || ''
      }
      if (type === 0) {
        api = projectInfoDownloadex
        this.xzmbLoading = true
      } else {
        api = projectInfoDownload
        this.dcLoading = true
      }
      api(param).then(res => {
        if (type === 0) {
          this.xzmbLoading = false
        } else {
          this.dcLoading = false
        }
        const blob = new Blob([res.data], {
          type: res.data.type + 'charset=utf-8'
        })
        const downloadLink = document.createElement('a')
        const URL = window.URL || window.webkitURL || window.moxURL
        const downUrl = URL.createObjectURL(blob)
        downloadLink.href = downUrl
        downloadLink.download = '项目信息管理.xlsx'
        downloadLink.click()
        window.URL.revokeObjectURL(downUrl)
        // document.body.removeChild(downloadLink) // 删除 a 标签
      })
    },
    handleUploadTemplate() {
      this.xzmbLoading = true
      // 下载模板
      // downTemplates().then(res => {
      //   const blob = new Blob([res.data], {
      //     type: res.data.type + 'charset=utf-8'
      //   })
      //   const downloadLink = document.createElement('a')
      //   const URL = window.URL || window.webkitURL || window.moxURL
      //   const downUrl = URL.createObjectURL(blob)
      //   downloadLink.href = downUrl
      //   downloadLink.download = '用户.xlsx'
      //   downloadLink.click()
      //   window.URL.revokeObjectURL(downUrl)
      //   // document.body.removeChild(downloadLink) // 删除 a 标签
      // })
    },
    handleCollection() {
      // 采集数据
      this.cjLoading = true
      collectFinancialData().then(res => {
        this.cjLoading = false
        if (res.data.code === 200) {
          this.cjTime = res.data.data
          this.$message.success(res.data.message)
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleEidt(row) {
      // 编辑
      this.currentRow = row
      this.handleClear()
      this.isShow = true
      this.handleSetFormValue(row)
    },
    handleClear() {
      for (const key in this.ruleForm) {
        if (key === 'allocations') {
          this.ruleForm[key] = [
            {
              createTime: '',
              appropriationBalance: '',
              financialCode: this.currentRow?.financialCode,
              financialName: this.currentRow?.financialName
            }
          ]
        } else {
          this.ruleForm[key] = ''
        }
      }
    },
    handleDelete(row) {
      this.$confirm({
        content: `您确定删除该条数据？`,
        title: '温馨提示',
        okFn: res => {
          projectInfoDelete({
            code: row.financialCode
          }).then(res => {
            if (res.data.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getData()
            }
          })
        },
        cancelFn: res => {
          console.log('取消')
        }
      })
    },
    handleSearch(value) {
      this.newCondition = value
      this.currentPage = 1
      this.getData(value)
    },
    getData() {
      const params = {
        entryId: this.newCondition?.entryId,
        financialCode: this.newCondition?.financialCode,
        leaderName: this.newCondition?.leaderName,
        projectName: this.newCondition?.projectName,
        projectCode: this.newCondition?.projectCode,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      this.tableLoading = true
      projectInfoPage(params)
        .then(res => {
          this.tableLoading = false
          if (res.data.code === 200) {
            this.tableData = res.data.data.list
            this.total = res.data.data.total
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch(() => {
          this.tableLoading = false
        })
    },
    handlerReset(val) {
      this.handleSearch()
    },
    pageChange(payload) {
      this.currentPage = payload.current
      this.pageSize = payload.pageSize
      this.getData()
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.el-table .warning-row {
  background: oldlace;
}
.form-box {
  padding: 10px 15px;
  box-sizing: border-box;
  .btn-xx {
    margin-top: 10px;
  }
  .z-j-box {
    position: absolute;
    right: 0px;
    width: 40px;
    display: flex;
    justify-content: space-between;
  }

  .label-text {
    display: flex;
    > span {
      margin-left: 10px;
    }
  }
  .label-fpjf {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }
  .el-icon-circle-plus-outline {
    // margin-right: 8px;
    color: #217dfa;
    font-size: 16px;
    cursor: pointer;
  }
  .el-icon-circle-close {
    font-size: 16px;
    cursor: pointer;
    color: #bd3124;
  }
}
.operation-box {
  margin-bottom: 10px;
}
.opt-right {
  display: flex;
  flex: 1;
  justify-content: flex-end;
}
.btn-import {
  height: 30px;
  display: flex;
  align-items: center;
  margin: 0px 10px;
  &:hover {
    background: white;
    color: #333;
    border: 1px solid #dedede;
  }
}
</style>
